#include<stdio.h>
#include<sys/wait.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define COMMAND_SIZE 32
#define SIZT_MAX 1024
int argc;
int exit_code;
char pwd[SIZT_MAX];
char*argv[COMMAND_SIZE];
char hostname[SIZT_MAX];
char command[SIZT_MAX];
char*getUser()
{
	return getenv("USER");
}
char*getHousename()
{
	gethostname(hostname,SIZT_MAX);
	return hostname;		
}
char*getPwd()
{
	return getenv("PWD");
}
void commandLine()
{

	printf("[%s@%s%s]#",getUser(),getHousename(),getPwd());
}
void printCommand(char*_command,size_t size)
{
	fgets(_command,size,stdin);
	_command[strlen(_command) - 1]= '\0';
}
void splitString()
{
	int i = 0;
	argv[i++] = strtok(command," ");
	while(argv[i++] = strtok(NULL," "));
	argc = i-1;
}
void make()
{
	pid_t id = fork();
	if(id < 0)
	{
		perror("fork");
		return;
	}
	else if(id == 0)
	{
		execvp(argv[0],argv);
		exit(44);
	}
	else
	{
		int status = 0;
		pid_t ret = wait(&status);
		if(ret == id)
		{
			exit_code = (status>>8)&0xff;
		}
		else 
		{
			perror("wait");
			return;
		}
	}
}
int myselfCommand()
{
	if(argc == 2&&strcmp(argv[0],"cd")==0)
	{
		//cd命令；
		chdir(argv[1]);
		//更新pwd;
		char*chpwd = getcwd(pwd,SIZT_MAX);
		if(!chpwd)
		{
			perror("getcwd");
		}
		else
		{
			sprintf(getenv("PWD"),"%s",pwd);
		}

		return 1;

	}
	else if(argc == 2&&strcmp(argv[0],"echo")==0)
	{
		 if(strcmp(argv[1],"$?")== 0)
		{
			printf("%d\n",exit_code);
			exit_code = 0;
		}
	  else	if((*argv[1]) == '$')
		{
			printf("%s\n",getenv(argv[1]+1));
		}
		else
		{
			printf("%s\n",argv[1]);
		}
		return 1;
	}
	return 0;
}
int main()
{
	int flog = 0;
	while(!flog)
	{
		//1:命令行提示符；
		commandLine();
		//输入命令；
		printCommand(command,sizeof(command));
		//分割命令；
		splitString();
		//内建命令；
		int n = myselfCommand();
		//创建子进程处理,普通命令
		if(!n)
	    make();	
	}
	return 0;
}
